import React, { Component, Fragment } from 'react';
import {
  Modal,
  Button,
  Form,
  Input,
  Select,
  message,
  Row,
  Col,
  Menu,
  Icon,
  Popover,
  Checkbox,
} from 'antd';
import Tree from '@/components/address/tree';
import Data from './regionData';
import styles from './selectAddress.less';
import {
  isEmptyArray,
  generateTreeDataMap,
  delMapItem,
  childrenChain,
  parentChain,
  findAllChildren,
  getFilterIdList,
  treeDataMapCheckRenderIdList,
  checkedCheckedList,
  getCheckedCount,
} from './tools';

const SubMenu = Menu.SubMenu;
const MenuItemGroup = Menu.ItemGroup;
export default class Region extends React.Component {
  constructor(props) {
    super(props);
    (this.state = {
      selectItemsId: [],
      selectItemsName: [],
      Data: [],
      checkedNameList: [],
    }),
      (this.checkedId = []),
      (this.checkedNames = []),
      (this.checkedNameList = []),
      (this.dataMap = {});
  }

  componentWillMount() {
    window.Isoption = false;
  }

  componentDidMount() {
    window.Isoption = true;
    //let arr = [320202, 320203, 320204, 320205, 320206, 320211, 320281, 320282];
    // let hideArr = [320102,320104,310101,310104];
    const { hideItems, selectItem } = this.props;
    this.dataMap = generateTreeDataMap(Data, {}, -1);   
    this.setState(
      {
        Data: JSON.parse(JSON.stringify(Data)),
      },
      () => {
        selectItem &&
          selectItem.RegionIds &&
          selectItem.RegionIds.length &&
          selectItem.RegionIds.forEach(item => {
            this.onCheckChange(
              { target: { checked: true } },
              this.dataMap[item].level,
              this.dataMap[item].rootIndex,
              this.dataMap[item].parentIndex,
              this.dataMap[item].subParentIndex,
              this.dataMap[item].index,
              this.dataMap[item].Id,
              this.dataMap[item].Name
            );
          });
        hideItems &&
          hideItems.length &&
          hideItems.forEach(item => {
            let value = this.dataMap[item];
            this.hideItem(
              value.level,
              value.rootIndex,
              value.parentIndex,
              value.subParentIndex,
              value.index
            );
          });
        const { Data } = this.state;
        let data = this.checkParentHide(Data);
        this.setState({
          Data: data,
        });
      }
    );
  }

  handleCancel = () => {
    const { _this } = this.props;
    _this.setState({ visible: false }, () => {
      this.forceUpdate();
    });
  };

  handleOk = () => {
    const { _this, selectItem } = this.props;
    const { selectItemsId, selectItemsName, checkedNameList } = this.state;
    if (selectItemsId.length < 1) {
      message.error('请选择配送地区');
      return;
    }
    console.log(this.state, this.props);

    const newDataId = selectItem == null ? Date.now() : selectItem.id;
    this.forceUpdate();
    if (selectItem != null) {
      const newData = {
        id: newDataId,
        FirstFee: selectItem.FirstFee,
        FirstAmount: selectItem.FirstAmount,
        AdditionalFee: selectItem.AdditionalFee,
        AdditionalAmount: selectItem.AdditionalAmount,
        RegionIds: selectItemsId,
        RegionNames: selectItemsName.split(','),
        RegionNamesShow: selectItemsName,
      };
      _this.handleAdd(newData);
    } else {
      const newData = {
        id: newDataId,
        FirstFee: 0,
        FirstAmount: 1,
        AdditionalFee: 0,
        AdditionalAmount: 1,
        RegionIds: selectItemsId,
        RegionNames: selectItemsName.split(','),
        RegionNamesShow: selectItemsName,
      };
      _this.handleAdd(newData);
    }
    _this.setState({ visible: false }, () => {});
  };

  checkedItem = (data, _ids, level = 0) => {
    const ids = [..._ids];
    const Data = data;
    //console.log(Data,220)
    ids &&
      ids.length &&
      ids.forEach(item => {
        Data.forEach(value => {
          if (item == value.Id) {
            value.checked = true;
            let ind = ids.findIndex(v => v == value.Id);
            ind > -1 ? ids.splice(ind, 1) : '';
            if (value.Child && value.Child.length) {
              this.checkedAllChild(value.Child, true);
              let arr = value.Child.filter(val => val.checked);
              if (value.Child.length == arr.length) {
              }
            }
          } else {
            if (value.Child && value.Child.length) {
              //this.checkedItem(value.Child,ids)
            }
          }
        });
      });
    return Data;
  };

  checkedAllChild = (data, checked) => {
    const Data = data;
    Data &&
      Data.forEach(item => {
        item.checked = checked;
        //item.halfChecked= !checked;
        if (item.Child && item.Child.length) {
          this.checkedAllChild(item.Child, checked);
        }
      });
    return Data;
  };

  IsHalfChecked = data => {
    //     const Data=data;
    //     let arr=[];
    //     if(Data&&Data.Child){
    //        if(!Data.checked){
    //         arr= Data.Child.filter((item)=>{
    //             return item.checked==true;
    //            })
    //        }else{
    //            return false;
    //        }
    //     }
    //    return Data&&Data.Child&&Data.Child.length&&arr.length?Data.Child.length !==arr.length:false;
    // const Data = data || {};
    // let arr = [];
    // if (Data && Data.Child && Data.Child.length) {
    //     arr = Data.Child.filter((item) => {
    //         return item.checked == true;
    //     })
    // }
    // if (Data.Child && Data.Child.length) {
    //     if (arr.length > 0) {
    //         if (Data.Child.length == arr.length) {
    //             return false;
    //         } else {
    //             return !Data.checked && !!arr.length;
    //         }
    //     } else {
    //         let arr = [];
    //         if (Data && Data.Child && Data.Child.length) {
    //             arr = Data.Child.filter((item) => {
    //                 return item.halfChecked == true;
    //             })
    //         }
    //         if (arr.length > 0) {
    //             return !Data.checked && !!arr.length;
    //         } else {
    //             if (!Data.checked && !Data.halfChecked) {
    //                 return Data.halfChecked;
    //             } else {
    //                 return !Data.halfChecked;
    //             }
    //         }
    //     }
    // }
    // return false;

    const Data = data;
    if (Data.Child && Data.Child.length) {
      Data.Child.forEach(item => {
        if (item.Child && item.Child.length) {
          item.Child.forEach(value => {
            if (value.Child && value.Child.length) {
              value.Child.forEach(val => {
                if (val.Child && val.Child.length) {
                  let count = val.Child.filter(v => v.checked && !v.isHide).length;
                  if (count > 0) {
                    if (val.Child.length == count) {
                      val.halfChecked = false;
                    } else {
                      val.halfChecked = true;
                    }
                  } else {
                    let counts = val.Child.filter(v => v.halfChecked && !v.isHide).length;
                    if (counts > 0) {
                      val.halfChecked = true;
                    } else {
                      val.halfChecked = false;
                    }
                  }
                }
              });
              let count = value.Child.filter(v => v.checked && !v.isHide).length;
              if (count > 0) {
                if (value.Child.length == count) {
                  value.halfChecked = false;
                } else {
                  value.halfChecked = true;
                }
              } else {
                let counts = value.Child.filter(v => v.halfChecked && !v.isHide).length;
                if (counts > 0) {
                  value.halfChecked = true;
                } else {
                  value.halfChecked = false;
                }
              }
            }
          });
          let count = item.Child.filter(v => v.checked && !v.isHide).length;
          if (count > 0) {
            if (item.Child.length == count) {
              item.halfChecked = false;
            } else {
              item.halfChecked = true;
            }
          } else {
            let counts = item.Child.filter(v => v.halfChecked && !v.isHide).length;
            if (counts > 0) {
              item.halfChecked = true;
            } else {
              item.halfChecked = false;
            }
          }
        }
      });
      let count = Data.Child.filter(v => v.checked && !v.isHide).length;
      if (count > 0) {
        if (Data.Child.length == count) {
          Data.halfChecked = false;
        } else {
          Data.halfChecked = true;
        }
      } else {
        let counts = Data.Child.filter(v => v.halfChecked && !v.isHide).length;
        if (counts > 0) {
          Data.halfChecked = true;
        } else {
          Data.halfChecked = false;
        }
      }
    }
    return Data;
  };

  IsChecked = data => {
    let Data = data || [];
    Data = Data.filter(v => !v.isHide);
    let arr = [];
    if (Data && Data.length) {
      arr = Data.filter(item => {
        return item.checked && !item.isHide;
      });
    }
    return Data.length == arr.length;
  };

  getCheckedCount = (item, count = 0) => {
    if (item.Child && item.Child.length) {
      item.Child.forEach((value, index) => {
        count = count + this.getChildCheckedCount(value);
      });
    }
    return count;
  };

  getChildCheckedCount = data => {
    let count = 0;
    if (data.Child && data.Child.length) {
      data.Child.forEach((value, index) => {
        if (value.checked && !value.isHide) {
          count = count + 1;
          //ids.push(value.Id)
        }
        if (value.Child && value.Child.length) {
          this.getChildCheckedCount(value.Child);
        }
      });
    } else {
      if (data.checked && !data.isHide) {
        count = count + 1;
      }
    }

    return count;
  };

  getCheckedIds = (data, checked) => {
    if (data.Child && data.Child.length) {
      data.Child.forEach((value, index) => {
        if (value.Child && value.Child.length) {
          this.getCheckedIds(value, checked);
        } else {
          if (checked && !value.isHide) {
            let index = this.checkedId.findIndex(item => item == value.Id);
            index > -1 && this.checkedId.splice(index, 1);
            index > -1 && this.checkedNameList.splice(index, 1);
            this.checkedId.push(value.Id);
            this.checkedNameList.push(value.Name);
          } else {
            let index = this.checkedId.findIndex(item => item == value.Id);
            index > -1 && this.checkedId.splice(index, 1);
            index > -1 && this.checkedNameList.splice(index, 1);
          }
        }
      });
    } else {
      if (checked && !data.isHide) {
        let index = this.checkedId.findIndex(item => item == data.Id);
        index > -1 && this.checkedId.splice(index, 1);
        index > -1 && this.checkedNameList.splice(index, 1);
        this.checkedId.push(data.Id);
        this.checkedNameList.push(data.Name);
      } else {
        let index = this.checkedId.findIndex(item => item == data.Id);
        index > -1 && this.checkedId.splice(index, 1);
        index > -1 && this.checkedNameList.splice(index, 1);
      }
    }
    return { checkedId: this.checkedId, checkedNameList: this.checkedNameList };
  };

  getAddressName = (_Data, _arr = []) => {
    // if(level==0){
    //     let index=this.checkedNames.findIndex((item)=>item===name);
    //     checked?this.checkedNames.push(name):index>-1?this.checkedNames.splice(index,1):'';
    // }else if(level==1){
    //     console.log(data)
    // }else if(level==2){

    // }else{

    // }
    //let count=this.getCheckedCount(data);
    //console.log(generateTreeDataMap(data.Child),333)
    //console.log(a,333)
    let arr = _arr;
    let idArr = [];
    let Data = _Data;
    Data.forEach(item => {
      if (item.Child && item.Child.length) {
        // let count=this.getCheckedCount(item);
        let count = item.Child.filter(function(v) {
          return v.checked;
        }).length;
        if (item.Child.length == count) {
            item.Child.forEach(values=>{
                if(!values.isHide){
                    arr.push(values.Name)
                }
            })
          //arr.push(item.Name);
          idArr.push(item.Id);
        } else {
          //this.getAddressName(item.Child,arr);
          item.Child.forEach((value, index) => {
            if (value.Child && value.Child.length) {
              let count = value.Child.filter(function(va) {
                return va.checked;
              }).length;
              if (value.Child.length == count) {
                arr.push(value.Name);
                idArr.push(value.Id);
              } else {
                value.Child.forEach((v, i) => {
                  if (v.Child && v.Child.length) {
                    let count = v.Child.filter(function(val) {
                      return val.checked;
                    }).length;
                    if (v.Child.length == count) {
                      arr.push(v.Name);
                      idArr.push(v.Id);
                    } else {
                      v.Child.forEach((vt, vi) => {
                        if (vt.Child && vt.Child.length) {
                          let count = v.Child.filter(function(val) {
                            return val.checked;
                          }).length;
                          if (vt.Child.length == count) {
                            arr.push(vt.Name);
                            idArr.push(vt.Id);
                          }
                        } else {
                          let idx = idArr.findIndex(a => a == vt.Id);
                          vt.checked ? arr.push(vt.Name) : idx > -1 ? arr.splice(idx, 1) : '';
                        }
                      });
                    }
                  } else {
                    let idx = idArr.findIndex(a => a == v.Id);
                    v.checked ? arr.push(v.Name) : idx > -1 ? arr.splice(idx, 1) : '';
                  }
                });
              }
            }
          });
        }
      }
    });
    return arr;
  };

  hideItem = (level, rootIndex, parentIndex, subParentIndex, index) => {
    const { Data } = this.state;
    if (level == 0) {
      Data[index].isHide = true;
    } else if (level == 1) {
      Data[subParentIndex].Child[index].isHide = true;
    } else if (level == 2) {
      Data[parentIndex].Child[subParentIndex].Child[index].isHide = true;
    } else {
      Data[rootIndex].Child[parentIndex].Child[subParentIndex].Child[index].isHide = true;
    }
    return Data;
  };

  hideparent = item => {
    // if (item.Child && item.Child.length) {
    //     item.Child.forEach((value, index) => {
    //         this.checkParentHide(value)
    //     })
    // }
  };

  checkParentHide = data => {
    // const {Data} = this.state;
    const Data = data;
    Data.forEach(item => {
      if (item.Child && item.Child.length) {
        item.Child.forEach(value => {
          if (value.Child && value.Child.length) {
            value.Child.forEach(val => {
              if (val.Child && val.Child.length) {
                let count = val.Child.filter(v => v.isHide).length;
                if (val.Child.length == count) {
                  val.isHide = true;
                }
              }
            });
            let count = value.Child.filter(v => v.isHide).length;
            if (value.Child.length == count) {
              value.isHide = true;
            }
          }
        });
        let count = item.Child.filter(v => v.isHide).length;
        if (item.Child.length == count) {
          item.isHide = true;
        }
      }
    });
    return Data;
  };

  onCheckChange = (e, level, rootIndex, parentIndex, subParentIndex, index, id, name) => {
    //console.log(e, level, rootIndex, parentIndex, subParentIndex, index, id, name)
    const { Data, selectItemsId, selectItemsName } = this.state;
    let checked = e.target.checked;
    let checkedIds = [];
    let checkedNames = [];
    let checkedNameList = [];
    if (level == 0) {
      Data[index].checked = checked;
      Data[index].Child = this.checkedAllChild(Data[index].Child, checked);
      let selectObj = this.getCheckedIds(Data[index], checked);
      checkedIds = selectObj.checkedId;
      checkedNameList = selectObj.checkedNameList;
    } else if (level == 1) {
      Data[subParentIndex].Child[index].checked = checked;
      Data[subParentIndex].Child[index].Child = this.checkedAllChild(
        Data[subParentIndex].Child[index].Child,
        checked
      );
      Data[subParentIndex].checked = this.IsChecked(Data[subParentIndex].Child);
      Data[subParentIndex] = this.IsHalfChecked(Data[subParentIndex]);
      //checkedIds = this.getCheckedIds(Data[subParentIndex].Child[index], checked).checkedId;
      let selectObj = this.getCheckedIds(Data[subParentIndex].Child[index], checked);
      checkedIds = selectObj.checkedId;
      checkedNameList = selectObj.checkedNameList;
    } else if (level == 2) {
      Data[parentIndex].Child[subParentIndex].Child[index].checked = checked;
      Data[parentIndex].Child[subParentIndex].Child[index].Child = this.checkedAllChild(
        Data[parentIndex].Child[subParentIndex].Child[index].Child,
        checked
      );
      Data[parentIndex].Child[subParentIndex].checked = this.IsChecked(
        Data[parentIndex].Child[subParentIndex].Child
      );
      Data[parentIndex].checked = this.IsChecked(Data[parentIndex].Child);
      Data[parentIndex] = this.IsHalfChecked(Data[parentIndex]);
      //checkedIds = this.getCheckedIds(Data[parentIndex].Child[subParentIndex].Child[index], checked).checkedId;
      let selectObj = this.getCheckedIds(
        Data[parentIndex].Child[subParentIndex].Child[index],
        checked
      );
      checkedIds = selectObj.checkedId;
      checkedNameList = selectObj.checkedNameList;
    } else {
      Data[rootIndex].Child[parentIndex].Child[subParentIndex].Child[index].checked = checked;
      Data[rootIndex].Child[parentIndex].Child[subParentIndex].Child[
        index
      ].Child = this.checkedAllChild(
        Data[rootIndex].Child[parentIndex].Child[subParentIndex].Child[index].Child,
        checked
      );
      Data[rootIndex].Child[parentIndex].Child[subParentIndex].checked = this.IsChecked(
        Data[rootIndex].Child[parentIndex].Child[subParentIndex].Child
      );
      Data[rootIndex].Child[parentIndex].checked = this.IsChecked(
        Data[rootIndex].Child[parentIndex].Child
      );
      Data[rootIndex].checked = this.IsChecked(Data[rootIndex].Child);
      // Data[rootIndex].Child[parentIndex].Child[subParentIndex].halfChecked = this.IsHalfChecked(Data[rootIndex].Child[parentIndex].Child[subParentIndex]);
      // Data[rootIndex].Child[parentIndex].halfChecked = this.IsHalfChecked(Data[rootIndex].Child[parentIndex]);
      // Data[rootIndex].halfChecked = this.IsHalfChecked(Data[rootIndex]);
      Data[rootIndex] = this.IsHalfChecked(Data[rootIndex]);
      //checkedIds = this.getCheckedIds(Data[rootIndex].Child[parentIndex].Child[subParentIndex].Child[index], checked).checkedId;
      let selectObj = this.getCheckedIds(
        Data[rootIndex].Child[parentIndex].Child[subParentIndex].Child[index],
        checked
      );
      checkedIds = selectObj.checkedId;
      checkedNameList = selectObj.checkedNameList;
    }
    // let idx=selectItemsId.findIndex(item=>item==id);
    // checked?selectItemsId.push(id):idx>-1?selectItemsId.splice(idx,1):'';
    // checked?selectItemsName.push(name):idx>-1?selectItemsName.splice(idx,1):'';

    this.setState(
      {
        Data,
        selectItemsId: checkedIds,
        checkedNameList,
        selectItemsName: this.getAddressName(Data).join(','),
      },
      () => {
        //console.log(this.state)
      }
    );
  };

  render() {
    const { visible, selectItem } = this.props;
    const { Data } = this.state;
    return (
      <div>
        <Modal
          visible={visible}
          title="选择地区"
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          width={800}
          bodyStyle={{ height: '485px' }}
          className={`${styles.tree} addressModal`}
        >
          <div style={{ overflow: 'hidden' }}>
            <div mode="vertical">
              {Data.map((items, indexs) => {
                return (
                  <div key={items.Id} style={{ width: '100%' }}>
                    {items.isHide ? null : (
                      <div
                        placement="rightTop"
                        className="aa"
                        getPopupContainer={() =>
                          document.querySelector(`.addressModal`) || document.body
                        }
                        trigger="hover"
                      >
                        <div style={{ width: 80, display: 'inline-block', verticalAlign: 'top' }}>
                          <Checkbox
                            onChange={e =>
                              this.onCheckChange(e, 0, -1, -1, -1, indexs, items.Id, items.Name)
                            }
                            checked={items.checked}
                            indeterminate={items.checked ? false : items.halfChecked}
                          >
                            {items.Name}
                          </Checkbox>
                        </div>
                        <div style={{ width: 'calc(100% - 80px)', display: 'inline-block' }}>
                          {items.Child.map((item, index) => {
                            const content = item.Child.map((v, i) => {
                              const areaContent = v.Child.map((val, ind) => {
                                return (
                                  <div
                                    style={{ paddingRight: 16, whiteSpace: 'nowrap' }}
                                    key={val.Id}
                                  >
                                    {val.isHide ? null : (
                                      <Checkbox
                                        onChange={e =>
                                          this.onCheckChange(
                                            e,
                                            3,
                                            indexs,
                                            index,
                                            i,
                                            ind,
                                            val.Id,
                                            val.Name
                                          )
                                        }
                                        checked={val.checked}
                                        // indeterminate={val.checked ? false : val.halfChecked}
                                      >
                                        {val.Name}
                                      </Checkbox>
                                    )}
                                  </div>
                                );
                              });
                              //console.log(areaContent)
                              return (
                                <div className="ww" style={{ overflow: 'hidden' }} key={v.Id}>
                                  {v.isHide ? null : areaContent.length ? (
                                    <Popover
                                      placement="rightTop"
                                      getPopupContainer={() =>
                                        document.querySelector(`.addressModal`) || document.body
                                      }
                                      content={areaContent}
                                      mouseEnterDelay={0.2}
                                      trigger="hover"
                                      key={v.Id}
                                    >
                                      <div style={{ paddingRight: 16, whiteSpace: 'nowrap' }}>
                                        <Checkbox
                                          onChange={e =>
                                            this.onCheckChange(
                                              e,
                                              2,
                                              -1,
                                              indexs,
                                              index,
                                              i,
                                              v.Id,
                                              v.Name
                                            )
                                          }
                                          checked={v.checked}
                                          indeterminate={v.checked ? false : v.halfChecked}
                                        >
                                          <span>{v.Name}</span>
                                          {(v.halfChecked || v.checked) &&
                                          this.getCheckedCount(v) ? (
                                            <span className="xkd-primary-color">
                                              ({this.getCheckedCount(v)})
                                            </span>
                                          ) : null}
                                          <Icon type="right" />
                                        </Checkbox>
                                      </div>
                                    </Popover>
                                  ) : (
                                    <div>
                                      <Checkbox
                                        onChange={e =>
                                          this.onCheckChange(
                                            e,
                                            2,
                                            -1,
                                            indexs,
                                            index,
                                            i,
                                            v.Id,
                                            v.Name
                                          )
                                        }
                                        checked={v.checked}
                                        indeterminate={v.checked ? false : v.halfChecked}
                                      >
                                        {v.Name}
                                      </Checkbox>
                                    </div>
                                  )}
                                </div>
                              );
                            });
                            return (
                              <Fragment key={item.Id}>
                                {item.isHide ? null : (
                                  <div
                                    style={{
                                      width: '25%',
                                      display: 'inline-block',
                                      marginBottom: 16,
                                    }}
                                    key={item.Id}
                                  >
                                    <Popover
                                      placement="rightTop"
                                      className="bb"
                                      getPopupContainer={() =>
                                        document.querySelector(`.addressModal`) || document.body
                                      }
                                      content={content}
                                      mouseEnterDelay={0.2}
                                      trigger="hover"
                                    >
                                      <div style={{ display: 'inline-block' }}>
                                        <Checkbox
                                          onChange={e =>
                                            this.onCheckChange(
                                              e,
                                              1,
                                              -1,
                                              -1,
                                              indexs,
                                              index,
                                              item.Id,
                                              item.Name
                                            )
                                          }
                                          checked={item.checked}
                                          indeterminate={item.checked ? false : item.halfChecked}
                                        >
                                          <span>{item.Name}</span>
                                          {(item.halfChecked || item.checked) &&
                                          this.getCheckedCount(item) ? (
                                            <span className="xkd-primary-color">
                                              ({this.getCheckedCount(item)})
                                            </span>
                                          ) : null}
                                          <Icon type="right" />
                                        </Checkbox>
                                      </div>
                                    </Popover>
                                  </div>
                                )}
                              </Fragment>
                            );
                          })}
                        </div>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        </Modal>
      </div>
    );
  }
}
